#include<iostream>
#include<unistd.h>
#include<string>
#include<cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include<cstdlib>
#include<cstdio>
#define N 2
#define NUM 1024
using namespace std;

void Write(int wfd)
{
    string s="I am child";
    int self=getpid();
    int num=0;
    
    char buffer[NUM];
    while(true)
    {
        //构建发送字符串
        buffer[0]=0;  //字符串清空，只是为了提醒阅读代码的人，我把这个数组当成字符串了
        snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",s.c_str(),self,num++);
        // cout<<buffer<<endl;
        //发送/写入给父进程
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }
}
void Read(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));  //read()的返回值为读取字符个数
        if(n>0)
        { 
            buffer[n]=0;  //0 == '\0
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
    }
}
int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0) return 1;
    // cout<<"pipefd[0]: "<<pipefd[0]<<",pipefd[1]"<<pipefd[1]<<endl;
    
    pid_t id =fork();
    if(id<0) return 2;
    //child->write  father->read
    else if(id==0)
    {
        //Child
        close(pipefd[0]);
        //IPC code
        
        Write(pipefd[1]);
        close (pipefd[1]);
        exit(0);
    }
    //Father
    close(pipefd[1]);

    //IPC code
    Read(pipefd[0]);

    int status=0;
    pid_t rid=waitpid(id,nullptr,0);
    if(rid<0) return 3;

    // cout<<"wait child success: "<<rid<<" exit code: "<<((status>>8)&0xFF)<<" exit signal: "<<(status&0x7F)<<endl;
    
    close(pipefd[0]);
    return 0;
}